package com.android.packageinstaller;
import java.util.Random;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

public class LoopProgressBar extends View {
  //短线的颜色，我们也可以开放一个setColor接口设置颜色
  private int color;

  //绘制短线的画笔
  private Paint paint;
  
  private  float space;
  
  //短线的宽度
  private  float lineWidth;

  //绘制短线的起点
  private int startX;

  Random random = new Random();
  public LoopProgressBar(Context context) {
    this(context, null);
  }

  public LoopProgressBar(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public LoopProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.LoopProgressBar);
    if(ta != null){
      color = ta.getColor(R.styleable.LoopProgressBar_lineColor, new Color().rgb(33, 177, 67));
      space = ta.getDimension(R.styleable.LoopProgressBar_space,  20);
      lineWidth = ta.getDimension(R.styleable.LoopProgressBar_lineWidth, 80);
    }
    if(ta != null){
      ta.recycle();
    }
    paint = new Paint();
    paint.setStyle(Paint.Style.FILL_AND_STROKE);
    paint.setColor(color);
    paint.setAntiAlias(true);
    paint.setStrokeCap(Paint.Cap.ROUND);
  }

  @Override protected void onDraw(Canvas canvas) {
    //整个控件的高度和宽度当执行到onDraw时已经layout了宽高早已经测量完成
    int w = getMeasuredWidth();
    int h = getMeasuredHeight();

    //Log.d(VIEW_LOG_TAG, "onDraw h : " + h);
    //每次重绘短线移动的距离
    int delta = 10;
    //画笔的宽度
    paint.setStrokeWidth(h+2);
    paint.setStrokeCap(Paint.Cap.ROUND);
    float start = startX;
    int randomValue = random.nextInt();
    delta = randomValue % 30;
    delta = Math.abs(delta);
    if(delta < 5){
    	delta += 10;
    }
    //Log.d(VIEW_LOG_TAG, "delta : " + delta);
    if((startX + lineWidth) > w){
    	canvas.drawLine(start, h/2, w,h/2, paint);
    	canvas.drawLine(0, h/2, (lineWidth - (w - start)) ,h/2, paint);
    }else{
    	canvas.drawLine(start, h/2, start + lineWidth,h/2, paint);
    }

	startX += delta;
	if(startX > w){
		startX = 0;
	}

    //延迟一定的时间重绘
    postInvalidateDelayed(100);
  }
}